﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PADWH35
{
    public partial class BlowJobStatusDialog : Form
    {
        Boolean isSlipJump = true;
        int AutoScorllInterval;
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 5:
                    datagv.Location = new Point(0, datagv.Top);
                    datagv.Size = new Size(panel1.Width, -datagv.Top + panel1.Height);
                    dataGridView1.Location = new Point(0, label1.Height);
                    dataGridView1.Size = new Size(this.ClientSize.Width, dataGridView1.ColumnHeadersHeight);
                    break;
            }
            base.WndProc(ref m);
        }

        public BlowJobStatusDialog()
        {
            InitializeComponent();
            this.Font = new Font(this.Font.Name, 12);
            IniHelper.SetIniPath(Application.StartupPath + @"\PADWH35.ini");
            string ASI = IniHelper.IniReadValue("BlowJobStatusDialog", "AutoScorllInterval");
            if (ASI == "") { ASI = "60000"; }
            SetMenuCheck("@" + ASI, false);
            datagv.AutoGenerateColumns = false;
            dataGridView1.Dock = DockStyle.Top; dataGridView1.Height = datagv.ColumnHeadersHeight;
            ColWidth(false);
        }

        Boolean isVerticalScrollBottom = true;
        int iStep = 0;
        int iSleep = Environment.TickCount;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (datagv.DisplayedRowCount(false) == datagv.RowCount || isVerticalScrollBottom)//如果datagv的数据不满一屏(没有竖直滚动条) 或 竖直滚动条到底
            {                                                                                //则刷新数据
                if (Environment.TickCount - iSleep > AutoScorllInterval || datagv.Rows.Count == 0)
                {
                    timer1.Enabled = false;
                    if (isSlipJump) { CopyGridFormat(); }
                    BindData();
                    timer1.Enabled = true;
                    isVerticalScrollBottom = false;
                    iSleep = Environment.TickCount;
                }
            }
            else
            {
                if (!isSlipJump)
                {
                    //datagv.FirstDisplayedScrollingRowIndex    设置/获取当前屏幕显示的第一行
                    //datagv.DisplayedRowCount(false)           返回向用户显示的行数
                    if (Environment.TickCount - iSleep > AutoScorllInterval)
                    {
                        datagv.FirstDisplayedScrollingRowIndex = datagv.FirstDisplayedScrollingRowIndex + datagv.DisplayedRowCount(false);
                        iSleep = Environment.TickCount;
                    }
                }
                else
                {
                    switch (iStep)
                    {
                        case 0:
                            if (Environment.TickCount - iSleep > AutoScorllInterval)
                            {
                                iStep++;
                            }
                            break;
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                            datagv.Top -= (int)((double)datagv.RowTemplate.Height * 0.05);
                            datagv.Height = panel1.Height - datagv.Top;
                            iStep++;
                            break;
                        case 21:
                            //pictureBox1.Size = this.ClientSize;
                            //pictureBox1.Image = GetScreenCapture();
                            //pictureBox1.Visible = true;
                            Application.DoEvents();
                            iStep++;
                            break;
                        case 22:
                            datagv.Top = 0;
                            datagv.FirstDisplayedScrollingRowIndex++;
                            datagv.Height = panel1.Height;
                            iStep++;
                            break;
                        case 23:
                            pictureBox1.Visible = false;
                            iSleep = Environment.TickCount;
                            iStep = 0;
                            break;
                    }
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            label2.Text = "当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //ColWidth(true);
        }

        private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            datagv.Columns[e.Column.Name].Width = e.Column.Width;
        }

        private void datagv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == ShowOnKanbanCol.Index)
            {
                datagv.EndEdit();
                ShowOnKanban(datagv[betriebsauftragnrCol.Index, e.RowIndex].FormattedValue.ToString(), datagv[ShowOnKanbanCol.Index, e.RowIndex].FormattedValue.ToString());
            }
        }

        private void datagv_Scroll(object sender, ScrollEventArgs e)
        {

            if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
            {
                if (e.NewValue + datagv.DisplayedRowCount(false) == datagv.RowCount)
                {
                    isVerticalScrollBottom = true;
                }
                label3.Text = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString() + "/" + (datagv.RowCount / datagv.DisplayedRowCount(false) + (datagv.RowCount % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                label3.Tag = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
            }
            else
            {
                if (isSlipJump)
                {
                    dataGridView1.FirstDisplayedScrollingColumnIndex = datagv.FirstDisplayedScrollingColumnIndex;
                    //dataGridView1.VerticalScrollingOffset = datagv.VerticalScrollingOffset;
                }
            }
        }

        private void mnuRefresh_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            BindData();
            timer1.Enabled = true;
        }

        private void mnuAutoScoll_Click(object sender, EventArgs e)
        {
            timer1.Enabled = !timer1.Enabled;
            this.mnuAutoScoll.CheckState = timer1.Enabled ? CheckState.Checked : CheckState.Unchecked;
            this.mnuScollInterval.Enabled = timer1.Enabled;
        }

        private void mnuXSecond_Click(object sender, EventArgs e)
        {
            SetMenuCheck(sender.ToString(), true);
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void BindData()
        {
            try
            {
                string sql = string.Empty;
                sql = "SELECT '' AS Page ,LIZENZ ,STANDORT ,BETRIEBSAUFTRAGNR ,AUFTRAGNR ,SOLLWERT ,P.NetWeight * SOLLWERT NetWeight ," + Environment.NewLine +
                      "    item1 ,item1Qty ,item1p ,item2 ,item2Qty ,item2p ,item3 ,item3Qty ,item3p ,item4 ,item4Qty ,item4p ," + Environment.NewLine +
                      "    item5 ,item5Qty ,item5p ,item6 ,item6Qty ,item7 ,item7Qty ,item8 ,item8Qty ,item9 ,item9Qty ,item10 ,item10p ," + Environment.NewLine +
                      "    1 AS ShowOnKanban" + Environment.NewLine +
                      "FROM Resin_Refill_View_Mei V" + Environment.NewLine +
                      "    LEFT JOIN Erp.Part P WITH(NOLOCK) ON V.AUFTRAGNR = P.PartNum AND P.Company = 'NSZ'";

                //Clipboard.Clear();
                //Clipboard.SetText(sql);

                DataTable dt = DBHelper.ExecuteDt(sql);
                datagv.DataSource = dt;

                //最后一页的行数不能达到一屏,补充差的行
                if (datagv.RowCount != datagv.DisplayedRowCount(false))
                {
                    int LessRow = datagv.DisplayedRowCount(false) - datagv.RowCount % datagv.DisplayedRowCount(false);
                    for (int j = 1; j <= LessRow; j++)
                    {
                        dt.Rows.Add();
                    }
                }
                //显示(当前页/总页数)
                label3.Text = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString() + "/" + (datagv.RowCount / datagv.DisplayedRowCount(false) + (datagv.RowCount % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                label3.Tag = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();

                //间隔双色显示
                for (int i = 0; i < datagv.Rows.Count; i++)
                {
                    if (i % 2 == 1)
                    {
                        for (int j = 0; j < datagv.Columns.Count; j++)
                        {
                            datagv.Rows[i].Cells[j].Style.BackColor = Color.FromArgb(240, 240, 240);
                        }
                    }
                    //页数
                    if (datagv.Rows[i].Cells[betriebsauftragnrCol.Index].Value.ToString() != "")
                    {
                        datagv.Rows[i].Cells[PageCol.Index].Value = ((i + 1) / datagv.DisplayedRowCount(false) + ((i + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                    }
                    //补充的差行用表格线颜色填充背景
                    if (datagv.Rows[i].Cells[betriebsauftragnrCol.Index].Value.ToString() == "")
                    {
                        for (int j = 0; j < datagv.Columns.Count; j++)
                        {
                            datagv.Rows[i].Cells[j].Style.BackColor = datagv.GridColor;
                        }
                    }
                }

                //除最后一列(是否在看板显示)以外全部只读
                for (int l = 0; l < datagv.Columns.Count; l++)
                {
                    if (l != ShowOnKanbanCol.Index)
                    {
                        datagv.Columns[l].ReadOnly = true;
                    }
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }

        private void ShowOnKanban(string JobNum_A_O, string Value)
        {
            JobNum_A_O = new string(JobNum_A_O.ToCharArray().Reverse<char>().ToArray<char>());//反转
            string OprSeq = JobNum_A_O.Substring(0, JobNum_A_O.IndexOf("-", 1));
            JobNum_A_O = JobNum_A_O.Substring(OprSeq.Length + 1);

            string AssemblySeq = JobNum_A_O.Substring(0, JobNum_A_O.IndexOf("-", 1));
            JobNum_A_O = JobNum_A_O.Substring(AssemblySeq.Length + 1);

            OprSeq = new string(OprSeq.ToCharArray().Reverse<char>().ToArray<char>());
            AssemblySeq = new string(AssemblySeq.ToCharArray().Reverse<char>().ToArray<char>());
            JobNum_A_O = new string(JobNum_A_O.ToCharArray().Reverse<char>().ToArray<char>());

            string SQLStr = "UPDATE JobOper SET CheckBox03 = '" + Value + "' WHERE JobNum = '" + JobNum_A_O + "' AND AssemblySeq = " + AssemblySeq + " AND OprSeq = " + OprSeq;
            //MessageBox.Show(SQLStr);
            DBHelper.ExecuteSql(SQLStr);
        }

        private void CopyGridFormat()
        {
            dataGridView1.Visible = true;
            dataGridView1.Columns.Clear();
            foreach (DataGridViewColumn col in datagv.Columns)
            {
                dataGridView1.Columns.Add(col.Name, col.HeaderText);
                dataGridView1.Columns[col.Name].Width = col.Width;
                dataGridView1.Columns[col.Name].Visible = col.Visible;
                dataGridView1.Columns[col.Name].DefaultCellStyle = col.DefaultCellStyle;
            }
        }

        private void SetMenuCheck(string Parameter1, Boolean Parameter1_textTRUE_tagFALSE)
        {
            ToolStripMenuItem mnu = (ToolStripMenuItem)contextMenuStrip1.Items["mnuScollInterval"];
            for (int i = 0; i < mnu.DropDownItems.Count; i++)   //循环mnuScollInterval下层所有菜单项
            {
                if (mnu.DropDownItems[i] is ToolStripMenuItem)  //如果是菜单项
                {
                    if ((string)(Parameter1_textTRUE_tagFALSE ? mnu.DropDownItems[i].Text : mnu.DropDownItems[i].Tag) == Parameter1)
                    {
                        ((ToolStripMenuItem)mnu.DropDownItems[i]).Checked = true;
                        AutoScorllInterval = int.Parse(mnu.DropDownItems[i].Tag.ToString().Substring(1));
                        IniHelper.IniWriteValue("BlowJobStatusDialog", "AutoScorllInterval", mnu.DropDownItems[i].Tag.ToString().Substring(1));
                    }
                    else
                    {
                        ((ToolStripMenuItem)mnu.DropDownItems[i]).Checked = false;
                    }
                }
            }
        }

        private Bitmap GetScreenCapture()//截图
        {
            Rectangle tScreenRect = new Rectangle(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Bitmap tSrcBmp = new Bitmap(tScreenRect.Width, tScreenRect.Height); // 用于屏幕原始图片保存
            Graphics gp = Graphics.FromImage(tSrcBmp);
            gp.CopyFromScreen(0, 0, 0, 0, tScreenRect.Size);
            gp.DrawImage(tSrcBmp, 0, 0, tScreenRect, GraphicsUnit.Pixel);
            return tSrcBmp;
        }

        public void ColWidth(Boolean IsGetOrSet)
        {
            if (IsGetOrSet)
            {
                string ClipText = string.Empty;
                for (int i = 0; i < datagv.Rows[0].Cells.Count; i++)
                {
                    ClipText += "datagv.Columns[@" + datagv.Columns[i].Name + "@].Width = " + datagv.Columns[i].Width + ";\t//" + datagv.Columns[i].HeaderText + Environment.NewLine;
                }

                Clipboard.Clear();
                Clipboard.SetText(ClipText);
            }
            else
            {
                datagv.Columns["PageCol"].Width = 30;               //页
                datagv.Columns["lizenzCol"].Width = 60;             //机台号
                datagv.Columns["standortCol"].Width = 50;           //仓号
                datagv.Columns["betriebsauftragnrCol"].Width = 140; //工单号
                datagv.Columns["auftragnrCol"].Width = 180;         //产品
                datagv.Columns["SOLLWERTCol"].Width = 100;          //数量
                datagv.Columns["NetWeightCol"].Width = 100;         //总重量
                datagv.Columns["item1pCol"].Width = 70;             //A百份比
                datagv.Columns["item2pCol"].Width = 70;             //B百份比
                datagv.Columns["item3pCol"].Width = 70;             //C百份比
                datagv.Columns["Dcol"].Width = 165;                 //D编号
                datagv.Columns["item10pCol"].Width = 70;            //D百份比
                datagv.Columns["item4Col"].Width = 165;             //物料4
                datagv.Columns["item4pCol"].Width = 70;             //物料4百分率
                datagv.Columns["item5Col"].Width = 165;             //物料5
                datagv.Columns["item5pCol"].Width = 70;             //物料5百分率
                datagv.Columns["item6Col"].Width = 165;             //色粉/色种
                datagv.Columns["item7Col"].Width = 165;             //添加剂 1
                datagv.Columns["item8Col"].Width = 165;             //添加剂 2
                datagv.Columns["item9Col"].Width = 165;	            //添加剂 3
                datagv.Columns["ShowOnKanbanCol"].Width = 60;	    //在看板上显示
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(label3.Tag) != 1)
            {
                datagv.FirstDisplayedScrollingRowIndex = (Convert.ToInt32(label3.Tag) - 2) * datagv.DisplayedRowCount(false);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if ((Convert.ToInt32(label3.Tag) + 0) * datagv.DisplayedRowCount(false) < datagv.Rows.Count)
            {
                datagv.FirstDisplayedScrollingRowIndex = (Convert.ToInt32(label3.Tag) + 0) * datagv.DisplayedRowCount(false);
            }
        }
    }
}
